<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-input
          placeholder="请将您要转换的汉文内容粘贴在这里"
          type="textarea"
          :rows="15"
          resize="none"
          v-model="input"
          clearable>
        </el-input>
      </el-col>
      <el-col :span="12">
        <el-input
          placeholder="请将您要转换的UTF-8内容粘贴在这里"
          type="textarea"
          :rows="15"
          resize="none"
          v-model="result"
          clearable>
        </el-input>
      </el-col>
    </el-row>
    <el-row style="float: right; margin-top: 10px">
      <el-button type="primary" @click="ChiToUtf8">中文 转 UTF-8</el-button>
      <el-button type="warning" @click="Utf8ToChi">UTF-8 转 中文</el-button>
      <el-button type="info" @click="reset">清空结果</el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'utf-8',
  data () {
    return {
      input: '',
      result: ''
    }
  },
  methods: {
    ChiToUtf8 () {
      if (!this.input) {
        this.openAlert('文本框不能为空')
        return
      }
      // eslint-disable-next-line
      this.result = this.input.replace(/[^\u0000-\u00FF]/g, function ($0) {
        return escape($0).replace(/(%u)(\w{4})/gi, '&#x$2;')
      })
    },
    Utf8ToChi () {
      if (!this.result) {
        this.openAlert('文本框不能为空')
        return
      }
      this.input = unescape(this.result.replace(/&#x/g, '%u').replace(/\\u/g, '%u').replace(/;/g, ''))
    },
    reset () {
      this.input = ''
      this.result = ''
    },
    // 弹框提示
    openAlert (msg) {
      this.$alert(msg, '错误提示', {
        confirmButtonText: '确定',
        callback: action => {}
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-input {
  padding: 10px
}
</style>
